<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 *  User Model Class  
 *  
 * @package XGO CMS v2.0 
 * @subpackage News  
 * @author Manh Nguyen - 03/08/2012 
 * @link http://sunsoft.vn
 */
class User_model extends DataMapper {

    var $model = 'user_model';
    var $table = 'users';

    // --------------------------------------------------------------------
    // Construct
    // --------------------------------------------------------------------	
    function __construct() {
        parent::__construct();
        $this->active = 1;
        $this->gender = 1;
    }

    // --------------------------------------------------------------------
    // Relationships
    // --------------------------------------------------------------------
    var $has_one = array(
        'group' => array(
            'class' => 'group_model',
            'other_field' => 'user'
        )
    );
    // --------------------------------------------------------------------
    var $has_many = array();
    // --------------------------------------------------------------------
    var $validation = array(
        'password' => array(
            'rules' => array('required', 'trim', 'min_length' => 3, 'max_length' => 40, 'encrypt'),
            'type' => 'password'
        ),
        'confirm_password' => array(
            'rules' => array('required', 'encrypt', 'matches' => 'password', 'min_length' => 3, 'max_length' => 40),
            'type' => 'password'
        ),
        'gender' => array(
            'values' => array(
                '0' => 'Nữ',
                '1' => 'Nam'
            )
        ),
        'active' => array(
            'values' => array(
                '0' => 'Không',
                '1' => 'Có'
            )
        )
    );

    // --------------------------------------------------------------------

    public function get_fullname_by_creator_or_editor($value = -1) {
        $fullname = '';
        $this->select('lastname,firstname')->where('id', $value)->get();
        $fullname = $this->lastname . " " . $this->firstname;
        return $fullname;
    }

    /**
     * Default order in query select 
     */
    var $default_order_by = array('lastname' => 'asc', 'firstname' => 'asc');

    // --------------------------------------------------------------------
    function fullname() {
        if (empty($this->firstname))
            return $this->lastname;
        return $this->firstname . ' ' . $this->lastname;
    }

    // --------------------------------------------------------------------
    /**
     * string value of object
     * 
     * @access private
     * @param null
     * @return string 
     */
    function __toString() {
        $fullname = $this->fullname();
        return empty($fullname) ? '--empty--' : $fullname;
    }

    // --------------------------------------------------------------------
    /**
     * check validate login of user
     * 
     * @access public
     * @param null
     * @return bool 
     */
    function login() {
        // backup username for invalid logins
        $username = $this->username;
        // Create a temporary user object
        $user = new User_model();
        $user->select('id, salt');

        // Get this users stored record via their username
        $user->where('username', $username)->get(1);

        // Give this user their stored salt
        $this->salt = $user->salt;

        // Validate and get this user by their property values,
        // this will see the 'encrypt' validation run, encrypting the password with the salt
        $this->validate()->get();

        // If the username and encrypted password matched a record in the database,
        // this user object would be fully populated, complete with their ID.
        // If there was no matching record, this user would be completely cleared so their id would be empty.
        if ($this->exists()) {
            if ($this->active <= 0) {
                $this->error_message('login', $this->localize_label('error_active'));
                return FALSE;
            }

            // Login succeeded
            $this->lastlogin = date(FORMATEDBDATETIME);
            $this->save();
            return TRUE;
        } else {
            // Login failed, so set a custom error message
            $this->error_message('login', $this->localize_label('error_login'));

            // restore username for login field
            $this->username = $username;
            return FALSE;
        }
    }

    /**
     * array gender of object
     * 
     * @access public
     * @param bool
     * @return array
     */
    function gender_list($zero = FALSE) {
        $gender_list = $this->validation['gender']['values'];
        if ($zero) {
            $gender_list = array_merge(array('' => '--'.$this->lang->line('all').'--'), $gender_list);
        }
        return $gender_list;
    }

    /**
     * array active of object
     *
     * @access public
     * @param bool
     * @return array
     */
    function active_list($zero = FALSE) {
        $active_list = $this->validation['active']['values'];
        if ($zero) {
            $active_list = array_merge(array('' => '--'.$this->lang->line('all').'--'), $active_list);
        }
        return $active_list;
    }

    /**
     * array group of object
     *
     * @access public
     * @param bool
     * @return array
     */
    function group_list($zero = FALSE) {
        $group = new Group_model();
        $group->select('id, title');
        $group_list = array();
        if ($zero) {
            $group_list[''] = '--'.$this->lang->line('all').'--';
        }
        foreach ($group->get_iterated() as $item) {
            $group_list[$item->id] = $item->title;
        }
        return $group_list;
    }

    /**
     * string value of active.
     *
     * @access public
     * @param void
     * @return string
     */
    function get_active() {
        if ($this->active <= 0)
            $active = 0; else
            $active = 1;
        return $this->validation['active']['values'][$active];
    }

    /**
     * generate salt and encrypt field.
     * user for encrypt password.
     * 
     * @access private
     * @param null
     * @return null 
     */
    function _encrypt($field) {
        if (!empty($this->{$field})) {
            if (empty($this->salt)) {
                $this->salt = md5(uniqid(rand(), TRUE));
            }
            $this->{$field} = sha1($this->salt . $this->{$field});
        }
    }

    // --------------------------------------------------------------------
    /**
     * check create object permit
     * 
     * @access public
     * @param obj
     * @return bool
     */
    function check_create($user = FALSE) {
        $group = new Group_model();
        $group->select('id,title');
        $group->where('id', $user->group->id);
        $group->get(1);
        $check = false;
        foreach ($group->role->get_iterated() as $role) {
            if ($role->keyword == 'user')
                $check = TRUE;
        }
        return $check;
    }

    // --------------------------------------------------------------------
    /**
     * check edit object permit
     * 
     * @access public
     * @param obj
     * @return bool
     */
    function check_edit($user = FALSE) {
        $group = new Group_model();
        $group->select('id,title');
        $group->where('id', $user->group->id);
        $group->get(1);
        $check = false;
        foreach ($group->role->get_iterated() as $role) {
            if ($role->keyword == 'user')
                $check = TRUE;
        }
        return $check;
    }

    // --------------------------------------------------------------------
    /**
     * check delete object permit
     * 
     * @access public
     * @param obj
     * @return bool
     */
    function check_delete($user = FALSE) {
        $group = new Group_model();
        $group->select('id,title');
        $group->where('id', $user->group->id);
        $user = $group->get(1);
        $check = false;

        foreach ($user->get_iterated() as $role) {
            if ($role->description == 'user')
                $check = TRUE;
        }
        return $check;
    }

    // --------------------------------------------------------------------
    /**
     * array metadata for generate jquery grid. 
     * 
     * @access public
     * @param null
     * @return array
     */
    function jqgrid_metadata() {
        return array(
            'names' => array(
                'id',
                $this->localize_label('username'),
                /* $this->localize_label('image'), */
                $this->localize_label('firstname'),
                $this->localize_label('lastname'),
                $this->localize_label('gender'),
                $this->localize_label('email'),
                $this->localize_label('phone'),
                $this->localize_label('address'),
                $this->lang->line('active'),
                $this->lang->line('group')
            ),
            'model' => array(
                array('name' => 'id', 'hidden' => TRUE, 'key' => TRUE,
                    'editrules' => array('edithidden' => TRUE)
                ),
                array('name' => 'username',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                /* 	array('name' => 'image',
                  'search' => FALSE
                  ), */
                array('name' => 'firstname',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'lastname',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'gender',
                    'searchoptions' => array(
                        'sopt' => array('eq'),
                        'value' => $this->gender_list(TRUE)
                    ),
                    'stype' => 'select'
                ),
                array('name' => 'email',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'phone',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'address',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'active',
                    'searchoptions' => array(
                        'sopt' => array('eq'),
                        'value' => $this->active_list(TRUE)
                    ),
                    'stype' => 'select'
                ),
                array('name' => 'group',
                    'searchoptions' => array(
                        'sopt' => array('eq'),
                        'value' => $this->group_list(TRUE)
                    ),
                    'stype' => 'select'
                )
            )
        );
    }
    
    function total(){
    	$this->select("count(id) as total");
    	$this->get();
    	 
    	return array(
    			"title" => $this->lang->line('user'),
    			"total"	=> $this->total,
    	);
    }
    

	function get_user_name($user_id = array()){
		$this->select("id, username");
		$this->where_in("id", $user_id);
		$this->get();
		return $this;
	}
}

/* End of file user.php */
/* Location: ./application/models/user.php */